package cn.edu.uestc.smgt.service.base.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.edu.uestc.smgt.common.QueryBase;
import cn.edu.uestc.smgt.common.StatusType;
import cn.edu.uestc.smgt.dao.AssistStudentMapper;
import cn.edu.uestc.smgt.dao.DeptMapper;
import cn.edu.uestc.smgt.dao.OfficeMapper;
import cn.edu.uestc.smgt.pojo.AssistStudent;
import cn.edu.uestc.smgt.pojo.Dept;
import cn.edu.uestc.smgt.pojo.Office;
import cn.edu.uestc.smgt.pojo.dto.AssistStudentDTO;
import cn.edu.uestc.smgt.service.base.AssistStudentService;
import cn.edu.uestc.smgt.utils.DAOResultUtil;

@Service("assistStudentService")
public class AssistStudentServiceImpl implements AssistStudentService {

	@Autowired
	private AssistStudentMapper assistStudentMapper;
	@Autowired
	private DeptMapper deptMapper;
	@Autowired
	private OfficeMapper officeMapper;

	// 增加助管信息
	public int add(AssistStudent ast) {
		if (ast == null || ast.getStuId() == null) {
			return StatusType.NOT_EXISTS.getVal();
		}
		if (assistStudentMapper.selectByStuId(ast.getStuId()) != null) {
			return StatusType.EXISTS.getVal();
		}
		int rows = assistStudentMapper.insertSelective(ast);
		return DAOResultUtil.getAddUpDateRemoveResult(rows, 0).getVal();
	}

	// 修改助管信息
	public int update(AssistStudent ast) {
		if (ast == null || ast.getStuId() == null
				|| assistStudentMapper.selectByStuId(ast.getStuId()) == null) {
			return StatusType.NOT_EXISTS.getVal();
		}

		int rows = assistStudentMapper.updateByStuIdSelective(ast);

		return DAOResultUtil.getAddUpDateRemoveResult(rows, 0).getVal();
	}

	// 删除助管信息
	public int delete(AssistStudent ast) {
		if (ast == null || ast.getStuId() == null
				|| assistStudentMapper.selectByStuId(ast.getStuId()) == null) {
			return StatusType.NOT_EXISTS.getVal();
		}
		int rows = assistStudentMapper.deleteByStuId(ast.getStuId());

		return DAOResultUtil.getAddUpDateRemoveResult(rows, 0).getVal();

	}

	// 查询助管信息
	public void query(QueryBase queryBase) {
		queryBase.setTotalRow(assistStudentMapper.size(queryBase
				.getParameters()));// 获取总行数
		List<AssistStudent> list = assistStudentMapper
				.selectByPageAndSelections(queryBase);
		List<AssistStudentDTO> listDto = new ArrayList<AssistStudentDTO>();
		for (AssistStudent ast : list) {
			AssistStudentDTO astDto = new AssistStudentDTO(ast);
			Dept dept;
			if (astDto.getDeptId() != null
					&& (dept = deptMapper.selectByDeptId(astDto.getDeptId())) != null)
				astDto.setDeptName(dept.getDeptName());

			Office office;
			if (astDto.getOfficeId() != null
					&& (office = officeMapper.selectByPrimaryKey(astDto
							.getOfficeId())) != null) {
				astDto.setOfficeName(office.getOfficeName());
			}
			listDto.add(astDto);
		}
		queryBase.setResults(listDto);// 获取需要返回的数据集
	}
}
